package cn.kill.stockservice.service.impl;

import cn.jbit.entity.User;
import cn.jbit.utils.ResResult;
import cn.kill.stockservice.common.Const;
import cn.kill.stockservice.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 源码学院只为培养优秀的bat程序员而生
 *
 * @author 学员张在成
 * @data 2021/6/2
 */
@Service
@Slf4j
@FeignClient("StockService")
public class StockServiceImpl implements StockService {

    @Autowired
    private StringRedisTemplate  redisTemplate;

    @Autowired
    private Redisson redisson;

    @Override
    public void saveStock() {
        redisTemplate.opsForValue().set(Const.key,"50");
    }

    //通过setnx加锁
    @Override
    public void delStock() {

        redisTemplate.opsForHash().put("kk",1,2);
        Object o=redisTemplate.opsForHash().get("kk",1);

        

        String requestId= UUID.randomUUID().toString();

        try {
            Boolean result=redisTemplate.opsForValue().setIfAbsent(Const.lock,requestId,10,TimeUnit.SECONDS);
            if (!result){
                log.info("系统繁忙，稍后再试");
                return;
            }
            //减库存
            Integer i = Integer.parseInt(redisTemplate.opsForValue().get(Const.key));
            if (i > 0) {
                int stock = i - 1;
                redisTemplate.opsForValue().set(Const.key, stock + "");
                System.out.println("扣减库存成功，剩余：" + stock);
            } else {
                System.out.println("库存不足");
            }

        }finally {
            if(requestId.equals(redisTemplate.opsForValue().get(Const.lock))) {
                redisTemplate.delete(Const.lock);
            }
        }
    }

    //通过Redission加锁
    @Override
    public void delStockRedssion() {

        //获取锁对象
        RLock lock=redisson.getLock(Const.lock);

        try {
            lock.lock(30,TimeUnit.SECONDS);
            //业务逻辑
            //从redis中查商品库存
            int stock=Integer.parseInt(redisTemplate.opsForValue().get(Const.key));
            if(stock>0){
                //减库存
                int stockDec=stock-1;
                System.out.println("扣减库存成功，商品剩余："+stockDec);
            }else {
                System.out.println("库存不足");
            }

        }finally {
            //释放锁
            lock.unlock();
        }

    }

    @Override
    public String lock(String key, String value) {
        return null;
    }

    @Override
    public void unLock() {

    }

    @Override
    public ResResult<User> loadUserByUsername(String username) {
        return null;
    }
}
